package com.ctz.commonframe.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;

import com.ctz.commonframe.entity.ImageItem;
import com.ctz.commonframe.ui.widget.FileChooseActivity;
import com.ctz.commonframe.ui.widget.ImageBucketChooseActivity;

@SuppressLint("NewApi")
public class PickImageUtil {
	public static final int REQUEST_CODE_TAKE_PHOTO = 30001;
	public static final int REQUEST_CODE_SELECT_IMAGE = 30002;
	public static final int REQUEST_CODE_PICK_FILE = 30003;

	private static PickImageUtil instance;

	private Activity activity;
	private OnPickImageResultListener listener;
	private String takePhotoPath;

	public interface OnPickImageResultListener {
		void onResult(List<ImageItem> imageList);
	}

	private PickImageUtil() {}

	public synchronized static PickImageUtil getInstance() {
		if (instance == null)
			instance = new PickImageUtil();
		return instance;
	}

	public void takePhoto(Activity activity, OnPickImageResultListener listener) {
		this.activity = activity;
		this.listener = listener;
		takePhotoPath = FilePathUtil.getImageFilePath(activity) + FilePathUtil.getImageFileName();
		File file = new File(takePhotoPath);
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		activity.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
	}

	public void selectImage(Activity activity, OnPickImageResultListener listener) {
		this.activity = activity;
		this.listener = listener;
		Intent intentImage = new Intent(activity, ImageBucketChooseActivity.class);
		activity.startActivityForResult(intentImage, REQUEST_CODE_SELECT_IMAGE);
	}

	public void pickFile(Activity activity, OnPickImageResultListener listener){
		this.activity = activity;
		this.listener = listener;
		Intent intent = new Intent(activity, FileChooseActivity.class);
        activity.startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
	}

	public void handleActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == Activity.RESULT_OK){
			switch (requestCode) {
                case REQUEST_CODE_TAKE_PHOTO:
                    ImageItem item = compressPhoto(activity, takePhotoPath);
                    List<ImageItem> list = null;
                    if(item != null){
                        list = new ArrayList<>();
                        list.add(item);
                    }
                    listener.onResult(list);
                    break;
                case REQUEST_CODE_SELECT_IMAGE:
                    List<ImageItem> selectedList = (List<ImageItem>) data.getSerializableExtra(ImageBucketChooseActivity.KEY_SELECTED_IMAGES);
                    List<ImageItem> compressedList = new ArrayList<>();
                    for (ImageItem oldItem: selectedList){
                        ImageItem newItem = compressPhoto(activity, oldItem.imagePath);
                        compressedList.add(newItem);
                    }
                    listener.onResult(compressedList);
                    break;
                case REQUEST_CODE_PICK_FILE:
                    ImageItem fileItem = (ImageItem) data.getSerializableExtra("file_data");
                    List<ImageItem> fileList = null;
                    if(fileItem != null){
                        fileList = new ArrayList<>();
                        fileList.add(fileItem);
                    }
                    listener.onResult(fileList);
                    break;

			}
		}else{
            switch (requestCode) {
                case REQUEST_CODE_TAKE_PHOTO:
                case REQUEST_CODE_SELECT_IMAGE:
                case REQUEST_CODE_PICK_FILE:
                    listener.onResult(null);
                    break;
            }

		}
	}
	
	private static ImageItem compressPhoto(Context context, String sourcePath) {
		final float scale = context.getResources().getDisplayMetrics().density;
		int destSize = (int) (80 * scale + 0.5f);
		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(sourcePath, bmOptions);
		int photoW = bmOptions.outWidth;
		int photoH = bmOptions.outHeight;
		int scaleFactor = Math.min(photoW / destSize, photoH / destSize);
		bmOptions.inJustDecodeBounds = false;
		bmOptions.inSampleSize = scaleFactor;
		Bitmap bitmap = BitmapFactory.decodeFile(sourcePath, bmOptions);
		saveBitmap(bitmap, sourcePath);
		if (saveBitmap(bitmap, sourcePath)) {
			ImageItem item = new ImageItem();
			item.imageName = new File(sourcePath).getName();
			item.size = String.valueOf(new File(sourcePath).length());
			item.imagePath = sourcePath;
			return item;
		}

		return null;
	}

	private static boolean saveBitmap(Bitmap bitmap, String savePath) {
		boolean result = false;
		File f = new File(savePath);
		FileOutputStream fOut;
		try {
            //noinspection ResultOfMethodCallIgnored
            f.delete();
			f.createNewFile();
			fOut = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
			fOut.flush();
			fOut.close();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
